#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "memheap.h"

/**********************************************************************************
 * 移植修改区
 */

/**
 * 互斥锁定
 */
static void mutex_lock(void)
{
/*
For MCU:

	 if not use rtos :
	     __disable_irq();
	 else
	     osMutexLock();
*/
}

/**
 * 互斥解锁
 */
static void mutex_unlock(void)
{
/*
For MCU:

	 if not use rtos :
	     __enable_irq();
	 else
	     osMutexUnlock();
*/
}



/**********************************************************************************
 * 内存管理实现
 */

#pragma pack(4)
static uint8_t memheap[MEMHEAP_SIZE];
#pragma pack()

/**
 * @ingroup BasicDef
 *
 * @def MH_ALIGN(size, align)
 * Return the most contiguous size aligned at specified width. MH_ALIGN(13, 4)
 * would return 16.
 */
#define MH_ALIGN(size, align)           (((size) + (align) - 1) & ~((align) - 1))

/**
 * @ingroup BasicDef
 *
 * @def MH_ALIGN_DOWN(size, align)
 * Return the down number of aligned at specified width. MH_ALIGN_DOWN(13, 4)
 * would return 12.
 */
#define MH_ALIGN_DOWN(size, align)      ((size) & ~((align) - 1))

#define HEAP_MAGIC 0x1ea01ea0

struct heap_mem
{
    /* magic and used flag */
    uint32_t magic;
    uint32_t used;
    size_t next;
    size_t prev;
};

/** pointer to the heap: for alignment, heap_ptr is now a pointer instead of an array */
static uint8_t *heap_ptr;

/** the last entry, always unused! */
static struct heap_mem *heap_end;

#define MEMHEAP_BLOCK_MIN_SIZE_ALIGNED     MH_ALIGN(MEMHEAP_BLOCK_MIN_SIZE, MH_ALIGN_SIZE)
#define SIZEOF_STRUCT_MEM    MH_ALIGN(sizeof(struct heap_mem), MH_ALIGN_SIZE)

static struct heap_mem *lfree;   /* pointer to the lowest free block */

static size_t mem_size_aligned;

#ifdef MEMHEAP_STATS
static size_t used_mem, max_mem;
#endif

static void plug_holes(struct heap_mem *mem)
{
    struct heap_mem *nmem;
    struct heap_mem *pmem;

    /* plug hole forward */
    nmem = (struct heap_mem *)&heap_ptr[mem->next];
    if (mem != nmem &&
        nmem->used == 0 &&
        (uint8_t *)nmem != (uint8_t *)heap_end)
    {
        /* if mem->next is unused and not end of heap_ptr,
         * combine mem and mem->next
         */
        if (lfree == nmem)
        {
            lfree = mem;
        }
        mem->next = nmem->next;
        ((struct heap_mem *)&heap_ptr[nmem->next])->prev = (uint8_t *)mem - heap_ptr;
    }

    /* plug hole backward */
    pmem = (struct heap_mem *)&heap_ptr[mem->prev];
    if (pmem != mem && pmem->used == 0)
    {
        /* if mem->prev is unused, combine mem and mem->prev */
        if (lfree == mem)
        {
            lfree = pmem;
        }
        pmem->next = mem->next;
        ((struct heap_mem *)&heap_ptr[mem->next])->prev = (uint8_t *)pmem - heap_ptr;
    }
}

/**
 * This function will initialize system heap memory.
 *
 * @param begin_addr the beginning address of system heap memory.
 * @param end_addr the end address of system heap memory.
 */
void memheap_init(void)
{
    struct heap_mem *mem;
    uint32_t begin_align = MH_ALIGN((uint32_t)memheap, MH_ALIGN_SIZE);
    uint32_t end_align   = MH_ALIGN_DOWN(((uint32_t)memheap) + MEMHEAP_SIZE, MH_ALIGN_SIZE);

    /* alignment addr */
    if ((end_align > (2 * SIZEOF_STRUCT_MEM)) &&
        ((end_align - 2 * SIZEOF_STRUCT_MEM) >= begin_align))
    {
        /* calculate the aligned memory size */
        mem_size_aligned = end_align - begin_align - 2 * SIZEOF_STRUCT_MEM;
    }
    else
    {
        return;
    }

    /* point to begin address of heap */
    heap_ptr = (uint8_t *)begin_align;

    /* initialize the start of the heap */
    mem        = (struct heap_mem *)heap_ptr;
    mem->magic = HEAP_MAGIC;
    mem->next  = mem_size_aligned + SIZEOF_STRUCT_MEM;
    mem->prev  = 0;
    mem->used  = 0;

    /* initialize the end of the heap */
    heap_end        = (struct heap_mem *)&heap_ptr[mem->next];
    heap_end->magic = HEAP_MAGIC;
    heap_end->used  = 1;
    heap_end->next  = mem_size_aligned + SIZEOF_STRUCT_MEM;
    heap_end->prev  = mem_size_aligned + SIZEOF_STRUCT_MEM;

    /* initialize the lowest-free pointer to the start of the heap */
    lfree = (struct heap_mem *)heap_ptr;
}

/**
 * Allocate a block of memory with a minimum of 'size' bytes.
 *
 * @param size is the minimum size of the requested block in bytes.
 *
 * @return pointer to allocated memory or NULL if no free memory was found.
 */
void *memheap_malloc(size_t size)
{
    size_t ptr, ptr2;
    struct heap_mem *mem, *mem2;

    if (size == 0)
        return NULL;

    /* alignment size */
    size = MH_ALIGN(size, MH_ALIGN_SIZE);

    if (size > mem_size_aligned)
    {
        return NULL;
    }

    /* every data block must be at least MEMHEAP_BLOCK_MIN_SIZE_ALIGNED long */
    if (size < MEMHEAP_BLOCK_MIN_SIZE_ALIGNED)
        size = MEMHEAP_BLOCK_MIN_SIZE_ALIGNED;

    mutex_lock();

    for (ptr = (uint8_t *)lfree - heap_ptr;
         ptr < mem_size_aligned - size;
         ptr = ((struct heap_mem *)&heap_ptr[ptr])->next)
    {
        mem = (struct heap_mem *)&heap_ptr[ptr];

        if ((!mem->used) && (mem->next - (ptr + SIZEOF_STRUCT_MEM)) >= size)
        {
            /* mem is not used and at least perfect fit is possible:
             * mem->next - (ptr + SIZEOF_STRUCT_MEM) gives us the 'user data size' of mem */

            if (mem->next - (ptr + SIZEOF_STRUCT_MEM) >=
                (size + SIZEOF_STRUCT_MEM + MEMHEAP_BLOCK_MIN_SIZE_ALIGNED))
            {
                /* (in addition to the above, we test if another struct heap_mem (SIZEOF_STRUCT_MEM) containing
                 * at least MEMHEAP_BLOCK_MIN_SIZE_ALIGNED of data also fits in the 'user data space' of 'mem')
                 * -> split large block, create empty remainder,
                 * remainder must be large enough to contain MEMHEAP_BLOCK_MIN_SIZE_ALIGNED data: if
                 * mem->next - (ptr + (2*SIZEOF_STRUCT_MEM)) == size,
                 * struct heap_mem would fit in but no data between mem2 and mem2->next
                 * @todo we could leave out MEMHEAP_BLOCK_MIN_SIZE_ALIGNED. We would create an empty
                 *       region that couldn't hold data, but when mem->next gets freed,
                 *       the 2 regions would be combined, resulting in more free memory
                 */
                ptr2 = ptr + SIZEOF_STRUCT_MEM + size;

                /* create mem2 struct */
                mem2       = (struct heap_mem *)&heap_ptr[ptr2];
                mem2->magic = HEAP_MAGIC;
                mem2->used = 0;
                mem2->next = mem->next;
                mem2->prev = ptr;

                /* and insert it between mem and mem->next */
                mem->next = ptr2;
                mem->used = 1;

                if (mem2->next != mem_size_aligned + SIZEOF_STRUCT_MEM)
                {
                    ((struct heap_mem *)&heap_ptr[mem2->next])->prev = ptr2;
                }
#ifdef MEMHEAP_STATS
                used_mem += (size + SIZEOF_STRUCT_MEM);
                if (max_mem < used_mem)
                    max_mem = used_mem;
#endif
            }
            else
            {
                /* (a mem2 struct does no fit into the user data space of mem and mem->next will always
                 * be used at this point: if not we have 2 unused structs in a row, plug_holes should have
                 * take care of this).
                 * -> near fit or excact fit: do not split, no mem2 creation
                 * also can't move mem->next directly behind mem, since mem->next
                 * will always be used at this point!
                 */
                mem->used = 1;
#ifdef MEMHEAP_STATS
                used_mem += mem->next - ((uint8_t *)mem - heap_ptr);
                if (max_mem < used_mem)
                    max_mem = used_mem;
#endif
            }
            /* set memory block magic */
            mem->magic = HEAP_MAGIC;

            if (mem == lfree)
            {
                /* Find next free block after mem and update lowest free pointer */
                while (lfree->used && lfree != heap_end)
                    lfree = (struct heap_mem *)&heap_ptr[lfree->next];
            }

            mutex_unlock();

            /* return the memory data except mem struct */
            return (uint8_t *)mem + SIZEOF_STRUCT_MEM;
        }
    }

    mutex_unlock();

    return NULL;
}

/**
 * This function will change the previously allocated memory block.
 *
 * @param rmem pointer to memory allocated by memheap_malloc
 * @param newsize the required new size
 *
 * @return the changed memory block address
 */
void *memheap_realloc(void *rmem, size_t newsize)
{
    size_t size;
    size_t ptr, ptr2;
    struct heap_mem *mem, *mem2;
    void *nmem;

    /* alignment size */
    newsize = MH_ALIGN(newsize, MH_ALIGN_SIZE);
    if (newsize > mem_size_aligned)
    {
        return NULL;
    }
    else if (newsize == 0)
    {
        memheap_free(rmem);
        return NULL;
    }

    /* allocate a new memory block */
    if (rmem == NULL)
        return memheap_malloc(newsize);

    mutex_lock();

    if ((uint8_t *)rmem < (uint8_t *)heap_ptr ||
        (uint8_t *)rmem >= (uint8_t *)heap_end)
    {
    	mutex_unlock();
        return rmem;
    }

    mem = (struct heap_mem *)((uint8_t *)rmem - SIZEOF_STRUCT_MEM);

    ptr = (uint8_t *)mem - heap_ptr;
    size = mem->next - ptr - SIZEOF_STRUCT_MEM;
    if (size == newsize)
    {
    	mutex_unlock();
        return rmem;
    }

    if (newsize + SIZEOF_STRUCT_MEM + MEMHEAP_BLOCK_MIN_SIZE < size)
    {
        /* split memory block */
#ifdef MEMHEAP_STATS
        used_mem -= (size - newsize);
#endif

        ptr2 = ptr + SIZEOF_STRUCT_MEM + newsize;
        mem2 = (struct heap_mem *)&heap_ptr[ptr2];
        mem2->magic = HEAP_MAGIC;
        mem2->used = 0;
        mem2->next = mem->next;
        mem2->prev = ptr;

        mem->next = ptr2;
        if (mem2->next != mem_size_aligned + SIZEOF_STRUCT_MEM)
        {
            ((struct heap_mem *)&heap_ptr[mem2->next])->prev = ptr2;
        }

        if (mem2 < lfree)
        {
            /* the splited struct is now the lowest */
            lfree = mem2;
        }

        plug_holes(mem2);

        mutex_unlock();

        return rmem;
    }

    mutex_unlock();

    /* expand memory */
    nmem = memheap_malloc(newsize);
    if (nmem != NULL) /* check memory */
    {
        memcpy(nmem, rmem, size < newsize ? size : newsize);
        memheap_free(rmem);
    }

    return nmem;
}

/**
 * This function will contiguously allocate enough space for count objects
 * that are size bytes of memory each and returns a pointer to the allocated
 * memory.
 *
 * The allocated memory is filled with bytes of value zero.
 *
 * @param count number of objects to allocate
 * @param size size of the objects to allocate
 *
 * @return pointer to allocated memory / NULL pointer if there is an error
 */
void *memheap_calloc(size_t count, size_t size)
{
    void *p;

    /* allocate 'count' objects of size 'size' */
    p = memheap_malloc(count * size);

    /* zero the memory */
    if (p)
        memset(p, 0, count * size);

    return p;
}

/**
 * This function will release the previously allocated memory block by
 * memheap_malloc. The released memory block is taken back to system heap.
 *
 * @param rmem the address of memory which will be released
 */
void memheap_free(void *rmem)
{
    struct heap_mem *mem;

    if (rmem == NULL)
        return;

    if ((uint8_t *)rmem < (uint8_t *)heap_ptr ||
        (uint8_t *)rmem >= (uint8_t *)heap_end)
    {
        return;
    }

    mem = (struct heap_mem *)((uint8_t *)rmem - SIZEOF_STRUCT_MEM);

    mutex_lock();
    
    mem->used  = 0;
    mem->magic = HEAP_MAGIC;

    if (mem < lfree)
    {
        /* the newly freed struct is now the lowest */
        lfree = mem;
    }

#ifdef MEMHEAP_STATS
    used_mem -= (mem->next - ((uint8_t *)mem - heap_ptr));
#endif

    /* finally, see if prev or next are free also */
    plug_holes(mem);

    mutex_unlock();
}

#ifdef MEMHEAP_STATS
void memheap_info(uint32_t *total, uint32_t *used, uint32_t *max_used)
{
    if (total != NULL)
        *total = mem_size_aligned;
    if (used  != NULL)
        *used = used_mem;
    if (max_used != NULL)
        *max_used = max_mem;
}
#endif
